package cn.edu.zsc.rbac.service.array;

import cn.edu.zsc.rbac.domain.dto.RoleDto;
import cn.edu.zsc.rbac.domain.entity.Role;
import cn.edu.zsc.rbac.domain.vo.RoleVo;
import cn.edu.zsc.rbac.domain.vo.Result;
import cn.edu.zsc.rbac.service.IRoleService;
import cn.edu.zsc.rbac.service.IUserService;

import java.util.Arrays;

/**
 * 业务层-角色
 *
 * @author
 * @since 2025/4/18 15:20
 */
public class RoleService extends BaseService<Role,RoleDto>implements IRoleService {


    private IUserService userService;

    private static IRoleService singleton;

    private RoleService() {
        data=new Role[DATA_SIZE+1];
    }

    public static IRoleService getInstance(){
        if(singleton==null){
            singleton = new RoleService();
        }
        return singleton;
    }



    public  RoleVo convertToVo(Role role){
        return new RoleVo(role.getId(),role.name,role.dataScope);
    }
    public  Role createEntity(RoleDto dto,int id){

        return new Role(id,dto.name,dto.dataScope);
    }
    public  void updateEntity(RoleDto dto,Role role){
        role.name=dto.name;
        role.dataScope=dto.dataScope;
    }




    @Override
    public  Result list(){
        RoleVo[] temp=new RoleVo[DATA_SIZE];
        int length=0;
        for (int i = 0; i < idCounter; i++) {
            if(data[i]!=null){
                temp[length++]=convertToVo(data[i]);
            }
        }
        return Result.success("查询成功",Arrays.copyOf(temp,length));
    }
    @Override
    public  Result create(RoleDto dto) {
        if(idCounter>DATA_SIZE){
            return Result.failure("创建失败，超出了存储容量");
        }
        Role role=createEntity(dto,idCounter++);
        data[role.getId()]=role;
        return Result.success("创建成功",null);
    }
    @Override
    public  Result update(RoleDto dto,int id) {
        if (!existsById(id)) {
            return Result.failure("更新失败，不存在该数据");
        }
        Role role=data[id];
        updateEntity(dto,role);
        return Result.success("更新成功", null);
    }

    @Override
    public  Result delete(int id) {
        if (!existsById(id)) {
            return Result.failure("删除失败，不存在该数据");
        }
        if(userService==null){
            userService=UserService.getInstance();
        }
        if(userService.roleInUse(id)){
            return Result.failure("删除失败，还有用户具有该角色，不能删除");
        }
        data[id]=null;
        return Result.success("删除成功", null);
    }
}
